package com.qdhh.enrollment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qdhh.enrollment.model.QuizQuestion;
import com.qdhh.enrollment.mapper.QuizQuestionMapper;
import com.qdhh.enrollment.service.QuizService;
import com.qdhh.enrollment.dto.QuestionImportDTO;
import com.qdhh.enrollment.util.ExcelImportUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class QuizServiceImpl implements QuizService {

    private final QuizQuestionMapper questionMapper;
    private final ObjectMapper objectMapper;

    public QuizServiceImpl(QuizQuestionMapper questionMapper) {
        this.questionMapper = questionMapper;
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public List<QuizQuestion> pickForExam(int total, Map<String, Integer> typeQuota) {
        List<QuizQuestion> all = questionMapper.selectList(null);
        
        if (typeQuota == null || typeQuota.isEmpty()) {
            // 随机选择
            Collections.shuffle(all);
            return all.stream().limit(total).collect(Collectors.toList());
        }

        // 按类型配额选择
        Map<String, List<QuizQuestion>> byType = all.stream()
            .collect(Collectors.groupingBy(QuizQuestion::getType));
        
        List<QuizQuestion> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : typeQuota.entrySet()) {
            String type = entry.getKey();
            int quota = entry.getValue();
            List<QuizQuestion> questions = byType.getOrDefault(type, Collections.emptyList());
            Collections.shuffle(questions);
            result.addAll(questions.stream().limit(quota).collect(Collectors.toList()));
        }
        
        return result;
    }

    @Override
    public int score(Map<String, String> submitted, List<QuizQuestion> questions) {
        int score = 0;
        for (QuizQuestion question : questions) {
            String userAnswer = submitted.getOrDefault(question.getId(), "");
            String correctAnswer = question.getAnswer();
            
            if (userAnswer.equalsIgnoreCase(correctAnswer)) {
                score += 10;
            }
        }
        return score;
    }

    @Override
    public List<QuizQuestion> listByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        QueryWrapper<QuizQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        return questionMapper.selectList(queryWrapper);
    }

    @Override
    public void seedSampleDataIfNeeded() {
        long count = questionMapper.selectCount(null);
        if (count == 0) {
            List<QuizQuestion> samples = new ArrayList<>();
            
            // 样本题目
            samples.add(createQuestion(
                "q1",
                "在宿舍内使用大功率电器是否安全？",
                "judge",
                null,
                "否",
                "1"
            ));
            
            samples.add(createQuestion(
                "q2",
                "学校图书馆开放时间是？",
                "single",
                "[\"8:00-18:00\",\"8:00-20:00\",\"9:00-21:00\",\"10:00-22:00\"]",
                "B",
                "1"
            ));
            
            saveBatch(samples);
        }
    }

    @Override
    public QuestionImportDTO importQuestionsFromCSV(InputStream inputStream) {
        QuestionImportDTO result = new QuestionImportDTO();
        
        try {
            // 解析CSV文件
            List<QuestionImportDTO.QuestionImportItem> items = ExcelImportUtil.parseCSV(inputStream);
            
            if (items.isEmpty()) {
                result.setErrorMessages(Collections.singletonList("未找到有效的题目数据"));
                return result;
            }
            
            // 转换为QuizQuestion对象
            List<QuizQuestion> questionsToSave = new ArrayList<>();
            int successCount = 0;
            int errorCount = 0;
            
            for (QuestionImportDTO.QuestionImportItem item : items) {
                try {
                    QuizQuestion question = convertItemToQuestion(item);
                    questionsToSave.add(question);
                    successCount++;
                } catch (Exception e) {
                    errorCount++;
                    result.getErrorMessages().add(
                        String.format("题目 '%s' 导入失败: %s",
                            item.getQuestionText().substring(0, Math.min(20, item.getQuestionText().length())),
                            e.getMessage())
                    );
                }
            }
            
            // 批量保存
            if (!questionsToSave.isEmpty()) {
                saveBatch(questionsToSave);
            }
            
            result.setSuccessCount(successCount);
            result.setItems(items);
            
            if (errorCount > 0) {
                result.getErrorMessages().add(
                    String.format("总计导入 %d 条，失败 %d 条", successCount + errorCount, errorCount)
                );
            }
            
            return result;
        } catch (Exception e) {
            result.getErrorMessages().add("文件解析失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    public void saveBatch(List<QuizQuestion> questions) {
        for (QuizQuestion question : questions) {
            if (question.getId() == null || question.getId().isEmpty()) {
                question.setId(UUID.randomUUID().toString().replace("-", ""));
            }
            if (question.getCreatedAt() == null) {
                question.setCreatedAt(LocalDateTime.now());
            }
            questionMapper.insert(question);
        }
    }

    /**
     * 将导入项转换为QuizQuestion
     */
    private QuizQuestion convertItemToQuestion(QuestionImportDTO.QuestionImportItem item) 
            throws Exception {
        
        // 验证必填字段
        if (item.getQuestionText() == null || item.getQuestionText().trim().isEmpty()) {
            throw new IllegalArgumentException("题目内容不能为空");
        }
        if (item.getCorrectAnswer() == null || item.getCorrectAnswer().trim().isEmpty()) {
            throw new IllegalArgumentException("正确答案不能为空");
        }
        
        // 类型验证
        String type = item.getType();
        if (!Arrays.asList("single", "multiple", "judge").contains(type)) {
            type = "single";
        }
        
        // 构建选项JSON
        String optionsJson = null;
        if (!type.equals("judge")) {
            List<String> options = new ArrayList<>();
            if (item.getOptionA() != null && !item.getOptionA().isEmpty()) {
                options.add(item.getOptionA());
            }
            if (item.getOptionB() != null && !item.getOptionB().isEmpty()) {
                options.add(item.getOptionB());
            }
            if (item.getOptionC() != null && !item.getOptionC().isEmpty()) {
                options.add(item.getOptionC());
            }
            if (item.getOptionD() != null && !item.getOptionD().isEmpty()) {
                options.add(item.getOptionD());
            }
            optionsJson = objectMapper.writeValueAsString(options);
        }
        
        QuizQuestion question = new QuizQuestion();
        question.setId(UUID.randomUUID().toString().replace("-", ""));
        question.setQuestion(item.getQuestionText());
        question.setType(type);
        question.setOptions(optionsJson);
        question.setAnswer(item.getCorrectAnswer());
        question.setScore(10);
        question.setCreatedAt(LocalDateTime.now());
        
        return question;
    }

    /**
     * 创建示例题目
     */
    private QuizQuestion createQuestion(String id, String question, String type, 
                                       String options, String correctAnswer, String score) {
        QuizQuestion q = new QuizQuestion();
        q.setId(id);
        q.setQuestion(question);
        q.setType(type);
        q.setOptions(options);
        q.setAnswer(correctAnswer);
        q.setScore(Integer.parseInt(score));
        q.setCreatedAt(LocalDateTime.now());
        return q;
    }
}

